<template>
  <div class="user-container">
    <div class="user-header">
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="formSearch.startTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="结束时间">
            <el-date-picker
              v-model="formSearch.endTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="所属城市" prop="citycode">
            <el-tree-select
              v-model="formSearch.citycode"
              :data="cityTreeOption"
              :props="defaultProps"
              node-key="Code"
              :check-strictly="true"
              :render-after-expand="false"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item label="场馆">
            <el-select
              v-model="formSearch.activityvenuescode"
              placeholder="--选择--"
              multiple
              collapse-tags
              collapse-tags-tooltip
              filterable
              clearable
            >
              <el-option
                v-for="item in activityVenuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="医疗点" prop="medicalPoint">
            <el-select
              v-model="formSearch.medicalPoint"
              placeholder="--选择--"
              clearable
              filterable
              ref="venuesRef"
            >
              <el-option
                v-for="item in medicalPointOption"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="患者姓名">
            <el-input v-model="formSearch.patientName" clearable> </el-input>
          </el-form-item>
          <el-form-item label="国籍（地区）">
            <el-input v-model="formSearch.nation" clearable> </el-input>
          </el-form-item>
          <el-form-item label="患者类别">
            <el-select
              v-model="formSearch.patient"
              placeholder="--请选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in patientOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="病情等级">
            <el-select
              v-model="formSearch.IllnessLevel"
              placeholder="--请选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in illnessLevelOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="送往医院" prop="SendHospital">
            <el-select
              v-model="formSearch.SendHospital"
              placeholder="--请选择--"
              filterable
              clearable
            >
              <el-option
                v-for="item in bindHospOptions"
                :key="item.Code"
                :label="item.ChineseName"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="疾病分类" prop="Classfy">
            <el-select
              v-model="formSearch.Classfy"
              placeholder="--请选择--"
              filterable
              clearable
            >
              <el-option
                v-for="item in classfyOptions"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="医院新增" prop="HospitalAdd">
            <el-select
              v-model="formSearch.HospitalAdd"
              placeholder="--请选择--"
              filterable
              clearable
            >
              <el-option
                v-for="item in bindHospOptions"
                :key="item.Code"
                :label="item.ChineseName"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否送院">
            <el-select
              v-model="formSearch.isSendHospi"
              placeholder="--请选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in isTestOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="user-main">
      <el-table
        ref="multipleTableRef"
        :data="patientList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column label="序号" type="index" :index="indexMethod">
        </el-table-column>
        <el-table-column property="Name" label="患者姓名" />
        <el-table-column property="patient" label="病历">
          <template #default="scope">
            <el-image
              :src="require('@/assets/patientCard.png')"
              @click="handleClick(scope.row.PatientRecordCode, 'view')"
            />
          </template>
        </el-table-column>
        <el-table-column property="Sex" label="性别" />
        <el-table-column property="Symptom1" label="症状" />
        <el-table-column property="VenuesName" label="场馆" />
        <el-table-column
          property="SeeADoctorDate"
          label="就诊时间"
          :formatter="timeFormat"
        />
        <el-table-column property="QX" label="到院后去向" />
        <el-table-column property="BQZG" label="病情转归" />
        <el-table-column property="Nationality" label="国籍（地区）" />
        <el-table-column property="IsClassFy" label="是否创伤">
          <template #default="scope">
            <el-tag
              class="mx-1"
              :type="scope.row.IsClassFy == 0 ? 'warning' : ''"
            >
              {{ scope.row.IsClassFy == 0 ? '创伤' : '非创伤' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="Telephone" label="联系方式" />
        <el-table-column property="StateName" label="状态" />
        <el-table-column property="SceneDoctor" label="现场医生" />
        <el-table-column property="AmbulanceDoctor" label="车辆医生" />
        <el-table-column property="HospitalDoctor" label="医院医生" />
        <el-table-column property="hospitalName1" label="医院" />
        <el-table-column property="HospitalName" label="送往医院" />
        <el-table-column label="操作" width="180px">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              v-btnpermission="'btn-patientrecordupdate'"
              :icon="Edit"
              @click="handleClick(scope.row.PatientRecordCode, 'update')"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              v-btnpermission="'btn-patientrecorddelete'"
              @click="DeleteDialog(scope.row.PatientRecordCode)"
              :icon="Delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total, prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue';
import { getPatientList, deletePatientRecord } from '@/network/patient';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import {
  getDicByDictionary,
  getActivityVenues,
  getCityTree,
  getMedicPointDicNormal,
  getBindHospi,
} from '@/network/dictionary.js';
import { receiveMsg } from '@/utils/crossTabMsg.js';

import store from '@/store';
const router = useRouter();
// console.log(router);
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const bindHospOptions = ref([]);
const classfyOptions = ref([]);
const illnessLevelOption = [
  {
    label: 'Ⅰ级（危急症）',
    value: 'Ⅰ级（危急症）',
  },
  {
    label: 'Ⅱ级（急重症）',
    value: 'Ⅱ级（急重症）',
  },
  {
    label: 'Ⅲ级（急症）',
    value: 'Ⅲ级（急症）',
  },
  {
    label: 'Ⅳ级（非急症）',
    value: 'Ⅳ级（非急症）',
  },
];
const isTestOption = [
  {
    label: '是',
    value: 1,
  },
  {
    label: '否',
    value: 0,
  },
];
const formSearch = reactive({
  startTime: getInitTime(7),
  endTime: getInitTime(0, ' 23:59:59'),
  nation: '',
  patient: '',
  patientName: '',
  page: 1,
  pageSize: 10,
  total: 0,
  activityvenuescode: null,
  medicalPoint: null,
  citycode: null,
  isSendHospi: null,
  IllnessLevel: null,
  SendHospital: null,
  HospitalAdd: null,
  Classfy: null,
});

//删除数据
const DeleteDialog = (id) => {
  ElMessageBox.confirm('确定删除吗?', '提示', {
    type: 'warning',
  })
    .then(async () => {
      await deletePatientRecord({ code: id })
        .then(() => {
          initData();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          ElMessage.warning(err.message);
          console.log(err);
        });
    })
    .catch(() => {
      console.log('取消');
    });
};

//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
const handleSelectionChange = (val) => {
  console.log(val);
};
let patientList = ref([]);
const handleCurrentChange = (val) => {
  formSearch.page = val;
  initData();
};
const onSubmit = () => {
  initData();
};
function timeFormat(row, column, v, i) {
  return moment(String(v)).format('YYYY-MM-DD HH:mm:ss');
}
//重置
const onReset = () => {
  formSearch.startTime = getInitTime(7);
  formSearch.endTime = getInitTime();
  formSearch.nation = '';
  formSearch.patient = '';
  formSearch.activityvenuescode = null;
  formSearch.medicalPoint = null;
  formSearch.citycode = null;
  formSearch.isTest = null;
  initData();
};
function getInitTime(intday, hour) {
  let secodenpast = new Date().getTime() - (intday || 0) * 24 * 60 * 60 * 1000;
  var now = new Date(secodenpast);
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth(); //得到月份
  var date = now.getDate(); //得到日期
  hour = hour || ' 00:00:00'; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
  month = month + 1;
  month = month.toString().padStart(2, '0');
  date = date.toString().padStart(2, '0');
  let x = `${year}-${month}-${date}${hour}`;
  return x;
}
//初始化数据
const initData = async () => {
  const params = {
    startTime: formSearch.startTime,
    endTime: formSearch.endTime,
    nation: formSearch.nation,
    patientname: formSearch.patientName,
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    citycode: formSearch.citycode,
    activityvenuescode: formSearch.activityvenuescode?.toString(),
    medicalPoint: formSearch.medicalPoint,
    isSendHospi: formSearch.isSendHospi,
    illnessLevel: formSearch.IllnessLevel,
    patient: formSearch.patient,
    Classfy: formSearch.Classfy,
    SendHospital: formSearch.SendHospital,
    HospitalAdd: formSearch.HospitalAdd,
  };
  await getPatientList(params).then((result) => {
    patientList.value = result.data;
    formSearch.total = result.total;
  });
};
//初始化字典
const nationOption = ref([]);
const patientOption = ref([]);
const venuesRef = ref(null);
const cityTreeOption = ref([]);
const activityVenuesOption = ref([]);
let medicalPointOptionArray = [];
let venuesOptionArray = [];
const medicalPointOption = ref([]);
const initDic = async () => {
  await getDicByDictionary({ type: 'nation' }).then((result) => {
    nationOption.value = result;
  });
  await getDicByDictionary({ type: 'PantientType' }).then((result) => {
    patientOption.value = result;
  });
  await getDicByDictionary({ type: 'ZDClassifyType' }).then((result) => {
    classfyOptions.value = result;
  });
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
  });
  await getActivityVenues().then((res) => {
    activityVenuesOption.value = res;
    venuesOptionArray = res;
  });
  await getMedicPointDicNormal().then((res) => {
    medicalPointOption.value = res;
    medicalPointOptionArray = res;
    // formSearch.medicalPoint = res[0].Code;
  });
  //获取医院
  await getBindHospi().then((res) => {
    bindHospOptions.value = res;
  });
  //监听watch
  watch(
    [() => formSearch.citycode, () => formSearch.activityvenuescode],
    (newValue, oldValue) => {
      // 城市变更--场馆变更--车辆变更--理疗店变更
      if (newValue[0] != oldValue[0]) {
        if (!newValue[0] || newValue[0] == 1) {
          activityVenuesOption.value = venuesOptionArray;
          medicalPointOption.value = medicalPointOptionArray;
        } else {
          formSearch.activityvenuescode = '';
          formSearch.medicalPoint = '';
          //车辆和医疗点、场馆都重新赋值
          activityVenuesOption.value = venuesOptionArray.filter(
            (it) => it.CityCode == newValue[0],
          );
          medicalPointOption.value = medicalPointOptionArray.filter(
            (it) => it.CityCode == newValue[0],
          );
        }
      }
      // 场馆变更   城市不变   车辆、医疗点变
      if (newValue[1] != oldValue[1]) {
        if (!newValue[1]) {
          if (newValue[0] && newValue[0] != 1) {
            medicalPointOption.value = medicalPointOptionArray.filter(
              (it) => it.CityCode == newValue[0],
            );
          } else {
            //医疗点重置
            medicalPointOption.value = medicalPointOptionArray;
          }
        } else {
          formSearch.medicalPoint = '';
          medicalPointOption.value = medicalPointOptionArray.filter(
            (it) => it.VenuesCode == newValue[1],
          );
        }
      }
    },
    {
      deep: true,
    },
  );
};
onMounted(() => {
  initDic().then(() => {
    initData();
  });
});
const cancelListener = receiveMsg((data) => {
  initData();
});
onUnmounted(cancelListener);
const handleClick = (patientId, type) => {
  let routeUrl = router.resolve({
    path: `/users/patient/${patientId}/${type}`,
  });
  window.open(routeUrl.href, '_blank');
  store.commit('app/setPath', `/users`);
};
</script>

<style lang="scss" scoped>
.user-container {
  // width: 100%;
  // background-color: #f1f2f6;
  // height: 100%;

  .user-header {
    margin: 14px 15px 14px;
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }

  .user-main {
    margin-left: 15px;
    margin-right: 15px;

    .user-pagination-block {
      position: fixed;
      bottom: 10px;
      left: 50%;
      transform: translate(-50%);
    }

    .user-pagination-block .el-pagination {
      justify-content: center;
    }
  }
}
</style>
